<template>
  <div>
    <a-button @click="() => { this.visible = true }">选择商品</a-button>

    <a-modal
      title="选择商品"
      :visible="visible"
      width="60%"
      :forceRender="true"
      @ok="handleOk"
      @cancel="handleCancel"
    >
      <div class="table-page-search-wrapper">
        <a-form :form="form" layout="inline" @submit="handleSearch">
          <a-row :gutter="24">
            <a-col :md="10" :sm="24">
              <a-form-item label="商品名称">
                <a-input v-model="queryParam.name" placeholder="" @keydown.enter.stop/>
              </a-form-item>
            </a-col>
            <a-col :md="10" :sm="24">
              <a-form-item label="商品分类">
                <commodity-category-selection v-model="queryParam.category"></commodity-category-selection>
              </a-form-item>
            </a-col>
            <a-col :md="4" :sm="24">
              <span class="table-page-search-submitButtons">
                <a-button type="primary" @click="handleSearch">查询</a-button>
              </span>
            </a-col>
          </a-row>
        </a-form>
      </div>

      <s-table
        ref="table"
        size="default"
        rowKey="id"
        :columns="columns"
        :data="loadData"
        showPagination="auto"
        :rowSelection="{ selectedRowKeys: selectedRowKeys, type: 'radio', onChange: handleChange }"
        :pageSize="5"
        :pageSizeOptions="['5', '10', '20', '30', '40']"
      >
        <span slot="pic" slot-scope="text, record">
          <img v-if="record.attachments[0]" width="100px" :src="record.attachments[0].url"/>
        </span>
      </s-table>
    </a-modal>
  </div>
</template>

<script>
  import CommodityCategorySelection from '@/components/CommodityCategorySelection/CommodityCategorySelection'
  import { STable } from '@/components'
  import { getCommodityList } from '@/api/commodity'

  export default {
    name: 'CommoditySelection',
    components: { CommodityCategorySelection, STable },
    props: {
      value: {
        type: Array,
        default: () => []
      },
      commodity: {
        type: Object,
        default: () => {
        }
      }
    },
    watch: {
      value: {
        handler: function (val) {
          this.selectedRowKeys = val
          // 有值 并且 之前没有默认选中的值, 才会进入初始化
          if (val.length > 0 && !this.hasDefaultSelectedCommodity) {
            this.orderById = val
            this.hasDefaultSelectedCommodity = true
            this.$refs.table.refresh() // 因为这里一开始渲染的时候没有被传入值,后传值的时候这里得刷新下列表
          }
        },
        immediate: true
      },
      commodity: {
        handler: function (val) {
          this.selectedCommodity = val
        },
        immediate: true
      }
    },
    data () {
      return {
        form: this.$form.createForm(this),
        visible: false,
        queryParam: {},
        columns: [
          {
            title: '图片',
            scopedSlots: { customRender: 'pic' }
          },
          {
            title: ' 分类',
            dataIndex: 'category.name'
          },
          {
            title: '商品名',
            dataIndex: 'name'
          }
        ],
        selectedRowKeys: this.value,
        selectedCommodity: this.selectedCommodity,
        orderById: [], // 编辑时,把之前选中的排序在前
        hasDefaultSelectedCommodity: false, // 编辑时要把一开始选中的商品抛出去一次
        selectedCommodityInitialized: false, // 编辑时 已经初始化完
        loadData: parameter => {
          if (this.orderById.length > 0) {
            parameter = Object.assign(parameter, { order_by_id: this.orderById })
          }
          const hasDefaultSelectedCommodity = this.hasDefaultSelectedCommodity
          const selectedCommodityInitialized = this.selectedCommodityInitialized

          return new Promise(resolve => {
            getCommodityList(Object.assign(parameter, this.queryParam))
              .then(res => {
                // 有选中的商品 && 没有初始化完成
                // 当"并发"时,这里的取值不能从 this 获取,故上面单独赋值
                if (hasDefaultSelectedCommodity && !selectedCommodityInitialized) {
                  this.selectedCommodityInitialized = true // 标记完成,防止再次进入, 比如第一页就有选中的商品时这里如果不加条件就会再次进入
                  res.data.forEach(item => {
                    if (this.selectedRowKeys.includes(item.id)) {
                      // 手动触发选择
                      this.handleChange([item.id], [item])
                      this.handleOk()
                    }
                  })
                }

                resolve(res)
              })
          })
        }
      }
    },
    methods: {
      handleOk () {
        this.$emit('input', this.selectedRowKeys)
        this.$emit('change', this.selectedCommodity)
        this.visible = false
      },
      handleCancel () {
        this.visible = false
      },
      handleSearch () {
        this.$refs.table.refresh()
      },
      handleChange (selectedId, record) {
        this.selectedRowKeys = selectedId
        const recordTemp = JSON.parse(JSON.stringify(record))
        // 在这里把 入仓价和进价 格式化为 元
        recordTemp[0].skus.forEach(sku => {
          sku.entry_price = sku.entry_price / 100
          sku.purchase_price = sku.purchase_price / 100
        })
        this.selectedCommodity = recordTemp
      }
    }
  }
</script>

<style scoped>

</style>
